package com.maixy.shorturldemo.controller;

import com.maixy.shorturldemo.service.UrlCenterService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @ClassName UrlCenterController
 * @Description TODO
 * @Date 2021/7/1 19:06
 * @Author maixingyu
 */
@RestController
@Slf4j
public class UrlCenterController {
    @Resource
    private UrlCenterService urlCenterService;

    @PostMapping("/url/center/createShortUrl")
    public String createShortUrl(@Param("longUrl") String longUrl) {
        if (StringUtils.isBlank(longUrl)) {
            throw new IllegalArgumentException();
        }
        return urlCenterService.createShortUrl(longUrl);
    }

    @GetMapping("/{urlKey}")
    public String getLongUrl(@PathVariable("urlKey") String urlKey) {
        log.info("urlKey:{}", urlKey);

        if ("favicon.ico".equals(urlKey)) {
            return "";
        }

        if (StringUtils.isBlank(urlKey)) {
            throw new IllegalArgumentException();
        }
        return urlCenterService.getLongUrl(urlKey);
    }
}
